package org.jsola.hr.web;

import lombok.extern.slf4j.Slf4j;
import org.jsola.hr.common.wechat.*;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.provider.ISiteConfigProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.service.IEmpInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * @author JanusMix
 */
@Slf4j
@Controller("hrWeChatOfficialAccountController")
@RequestMapping(HrConstants.API_PATH + "/v1/weChatOfficialAccount")
public class WeChatOfficialAccountController implements WeChatOfficialAccountControllerAPI {

    @Autowired
    private IUserProviderService userProviderService;

    @Autowired
    private IEmpInfoService empInfoService;

    @Autowired
    private MessageHandlerUtil messageHandlerUtil;

    @Autowired
    private WeChatEvent weChatEvent;

    @Autowired
    private ISiteConfigProviderService siteConfigProviderService;

    @Override
    @GetMapping(value = "/weChatHandle")
    public void weChatGet(
            String signature,
            String timestamp,
            String nonce,
            String echostr,
            HttpServletRequest request,
            HttpServletResponse response) {
        PrintWriter out = null;
        try {
            request.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.write(echostr);
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                log.info("连接微信公众号平台测试成功！");
            }
        } catch (Exception e) {
            log.error("连接微信公众号平台测试失败！",e);
        } finally {
            out.close();
        }
    }

    @Override
    @PostMapping(value = "/weChatHandle")
    public void weChatPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 接受微信推送事件的一个接口
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String result = "";

        PrintWriter out = null;
        try {
            Map<String, String> map = MessageHandlerUtil.parseXml(request);
            // 租户id
            String tenantId = request.getParameter("tenantId");
            // 公众号名称（admin是管理端）
            String account = request.getParameter("account");
            // 公众号类型
            String type = request.getParameter("type");
            log.info("微信回调, 租户id: {},公众号名称: {}", tenantId, account);
            switch (map.get("MsgType")) {
                //根据时间类型不同，进行相应的回复
                case "event":
                    result = weChatEvent.choose(map, tenantId, account, type);
                    request.setCharacterEncoding("UTF-8");
                    out = response.getWriter();
                    out.write(result);
                    return;
                case "text":

                    break;
                case "image":

                    break;
                case "voice":

                    break;
                case "video":

                    break;
                case "shortvideo":

                    break;
                case "location":

                    break;
                case "link":

                    break;
                default:
                    break;
            }

            String content = ("谢谢您关注" + account);
            result = BuildWXMessage.buildTextMessage(map, content);

            log.info(result);
            if ("".equals(result)) {
                result = "未正确响应";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发生异常：" , e);
        }


        try {
            request.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.write(result);
        } catch (Exception e) {
            log.error("连接微信公众号平台测试失败！",e);
        } finally {
            out.close();
        }
    }

    /**
     * 创建自定义菜单:
     */
    @RequestMapping("/createWeChatMenu")
    @ResponseBody
    public String createWeChatMenu() {
        // TODO 写入appid,秘钥
        String appId = "";
        String appSecret = "";
        String accessToken = MessageHandlerUtil.getAccessToken(appId, appSecret).getAccessToken();
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
        log.info("发送的url" + tokenUrl);
        String menu = "{\n" +
                "     \"button\":[\n" +
                "     {\t\n" +
                "          \"type\":\"miniprogram\",\n" +
                "          \"name\":\"员工服务\",\n" +
                "          \"url\":\"https://hr.csxr.cn/register.html\",\r\n" +
                "          \"appid\":\"" + appId + "\",\r\n" +
                "          \"pagepath\":\"pages/index/index\"\r\n" +
                "      }]\n" +
                " }";
        try {
            URL url = new URL(tokenUrl);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒

            http.connect();
            OutputStream os = http.getOutputStream();
            os.write(menu.getBytes("UTF-8"));//传入参数
            os.flush();
            os.close();

            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            return "返回信息" + message;
        } catch (Exception e) {
            log.error("createWeChatMenu异常: ",e);
        }
        return "createMenu 失败";
    }

    /**
     * 删除自定义菜单:
     */
    @RequestMapping("/deleteWeChatMenu")
    @ResponseBody
    public String deleteWeChatMenu() {
        // TODO 写入appid,秘钥
        String appId = "";
        String appSecret = "";
        String accessToken = MessageHandlerUtil.getAccessToken(appId, appSecret).getAccessToken();
        String action = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken;
        try {
            URL url = new URL(action);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒

            http.connect();
            OutputStream os = http.getOutputStream();
            os.flush();
            os.close();

            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            return "deleteMenu返回信息:" + message;
        } catch (Exception e) {
            log.error("deleteWeChatMenu异常：", e);
        }
        return "deleteMenu 失败";
    }
}
